#!/usr/bin/env python
# --coding:utf-8--

import urllib
import random
from BaseHTTPServer import BaseHTTPRequestHandler, HTTPServer
from os import path
from urlparse import urlparse

from tornado.escape import json_encode

# 自定义
from core.anaysis import dealWords

curdir = path.dirname(path.realpath(__file__))
sep = '/'

# MIME-TYPE
mimedic = [
    ('.html', 'text/html'),
    ('.htm', 'text/html'),
    ('.js', 'application/javascript'),
    ('.css', 'text/css'),
    ('.json', 'application/json'),
    ('.png', 'image/png'),
    ('.jpg', 'image/jpeg'),
    ('.gif', 'image/gif'),
    ('.txt', 'text/plain'),
    ('.avi', 'video/x-msvideo'),
    ('.ico', 'text/text'),
]


class HTTPServer_RequestHandler(BaseHTTPRequestHandler):
    # GET
    def do_GET(self):
        sendReply = False
        querypath = urlparse(self.path)
        filepath, query = querypath.path, querypath.query

        if filepath.endswith('/'):
            filepath += 'index.html'
        filename, fileext = path.splitext(filepath)
        for e in mimedic:
            if e[0] == fileext:
                mimetype = e[1]
                sendReply = True

        if sendReply == True:
            try:
                with open(path.realpath(curdir + sep + filepath), 'rb') as f:
                    content = f.read()
                    self.send_response(200)
                    self.send_header('Content-type', mimetype)
                    self.end_headers()
                    self.wfile.write(content)
            except IOError:
                self.send_error(404, 'File Not Found: %s' % self.path)

    # POST
    def do_POST(self):
        result = {}
        # Python3
        # length = int(self.headers['Content-Length'])
        # post_data = urllib.parse.parse_qs(self.rfile.read(length).decode('utf-8'))

        # Python2
        post_data = self.rfile.read(int(self.headers['content-length']))
        datas = urllib.unquote(post_data)
        content = datas.split('=')

        dealWordsModle = dealWords(content[1])
        dealWordsModle.draw_wordcloud()
        result["url"] = 'http://localhost:8000/wordcloud.jpg?v=' + ''.join(
            random.sample(['h', 'g', 'f', 'e', 'd', 'c', 'b', 'a'], 5))

        self.send_response(200)
        self.send_header('Content-type', 'application/json')
        self.end_headers()
        self.wfile.write(json_encode(result).encode('utf-8'))


def run():
    port = 8000
    print('starting server, port', port)

    # Server settings
    server_address = ('', port)
    httpd = HTTPServer(server_address, HTTPServer_RequestHandler)
    print('running server...')
    httpd.serve_forever()


if __name__ == '__main__':
    run()
